/**
 * 
 */
package com.google.code.jkippt.parser;

import java.util.Calendar;


import com.google.code.jkippt.resource.Account;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * JSon parser for incoming and outcoming messages.
 * @author Federico De Faveri defaveri@gmail.com
 */
public class Parser {

	protected Gson gson;

	public Parser()
	{
		GsonBuilder gsonBuilder = new GsonBuilder();
		gsonBuilder.registerTypeAdapter(Calendar.class, new CalendarAdapter());
		gson = gsonBuilder.create();
	}

	/**
	 * Parsers a JSON string as an {@link Account} object.
	 * @param json
	 * @return
	 */
	public Account parseAccount(String json)
	{
		return gson.fromJson(json, Account.class);
	}

	/**
	 * Creates a new {@link PageParserBuilder} for the specified type.
	 * @param type
	 * @return
	 * @throws ParserException
	 */
	public <T> PageParserBuilder<T> getPageParserBuilder(Class<T> type) throws ParserException
	{
		return new PageParserBuilder<T>(gson, type);
	}
	
	/**
	 * Converts the specified JSON in the specified class instance.
	 * @param json
	 * @param type
	 * @return
	 */
	public <T> T parse(String json, Class<T> type)
	{
		return gson.fromJson(json, type);
	}
	
	/**
	 * Convert the specified object instance in a JSON string.
	 * @param item
	 * @return
	 */
	public <T> String toJson(T item)
	{
		return gson.toJson(item);
	}

}
